<?php

/**
 * echantillon actions.
 *
 * @package    appcemhti
 * @subpackage echantillon
 * @author     Steve Cancès
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class echantillonActions extends sfActions
{
    protected function droitLecture()
    {
        $droitUtilisateur = $this->lot->idDroitSurLot($this->getUser()->getGuardUser()->getId());
        $this->forwardUnless($droitUtilisateur == 3 || $droitUtilisateur == 2, 'sfGuardAuth', 'secure');
    }
    
    protected function droitEcriture()
    {
        $droitUtilisateur = $this->lot->idDroitSurLot($this->getUser()->getGuardUser()->getId());
        $this->forwardUnless($droitUtilisateur == 3, 'sfGuardAuth', 'secure');
    }

    public function executeShow(sfWebRequest $request)
    {
        $this->forward404Unless($this->echantillon = Doctrine_Core::getTable('Echantillon')->find(array($request->getParameter('id_echantillon'))), sprintf('Object echantillon does not exist (%s).', $request->getParameter('id_echantillon')));
        $this->lot = $this->echantillon->getLot();
        
        // On vérifie que l'utilisateur a les droits de lecture sur le lot concerné
        $this->droitLecture();
        
        $this->nbTraitementSurLot = $this->echantillon->getLot()->getTraitement()->count();
        
        $this->nbTraitement = $this->echantillon->getNbTraitement();
        $this->nbMesure = $this->echantillon->getMesure()->count();
        $this->nbCommentaireSurEchantillon = $this->echantillon->getCommentaire()->count();
        $this->nbCommentaireSurLot = $this->lot->getCommentaire()->count();
        
        $this->typesTraitement = Doctrine_Core::getTable('typeTraitement')->findAll();
    }

    public function executeNew(sfWebRequest $request)
    {
        $this->forward404Unless($this->lot = Doctrine_Core::getTable('lot')->find(array($request->getParameter('id_lot'))), sprintf('Object lot does not exist (%s).', $request->getParameter('id_lot')));
        
        // On vérifie que l'utilisateur a les droits d'écriture sur le lot concerné
        $this->droitEcriture();
        
        $this->echantillon = new Echantillon();
        $this->echantillon->setLot($this->lot);
        $this->form = new echantillonForm($this->echantillon);
    }

    public function executeCreate(sfWebRequest $request)
    {
        $this->forward404Unless($request->isMethod(sfRequest::POST));
        $this->forward404Unless($this->lot = Doctrine_Core::getTable('lot')->find(array($request->getParameter('id_lot'))), sprintf('Object lot does not exist (%s).', $request->getParameter('id_lot')));

        // On vérifie que l'utilisateur a les droits d'écriture sur le lot concerné
        $this->droitEcriture();
        
        $this->form = new echantillonForm();

        $params = $request->getParameter($this->form->getName());
        if(isset($params['rectangle'])) $params['rectangle'] = 1;
        else $params['rectangle'] = null;
        $params['id_lot'] = $this->lot->getIdLot();
        $params['created_at'] = date('Y-m-d H:i:s', time());
        $params['updated_at'] = date('Y-m-d H:i:s', time());
        $params['id_user'] = $this->getUser()->getGuardUser()->getId();
        $request->setParameter($this->form->getName(), $params);

        $this->processForm($request, $this->form);

        $this->setTemplate('new');
    }

    public function executeEdit(sfWebRequest $request)
    {
        $this->forward404Unless($this->echantillon = Doctrine_Core::getTable('echantillon')->find(array($request->getParameter('id_echantillon'))), sprintf('Object echantillon does not exist (%s).', $request->getParameter('id_echantillon')));
        $this->form = new echantillonForm($this->echantillon);
        $this->lot = $this->echantillon->getLot();
        
        // On vérifie que l'utilisateur a les droits d'écriture sur le lot concerné
        $this->droitEcriture();
    }

    public function executeUpdate(sfWebRequest $request)
    {
        $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
        $this->forward404Unless($this->echantillon = Doctrine_Core::getTable('echantillon')->find(array($request->getParameter('id_echantillon'))), sprintf('Object echantillon does not exist (%s).', $request->getParameter('id_echantillon')));
        $this->lot = $this->echantillon->getLot();
        $this->form = new echantillonForm($this->echantillon);
        
        // On vérifie que l'utilisateur a les droits d'écriture sur le lot concerné
        $this->droitEcriture();

        $params = $request->getParameter($this->form->getName());
        if($params['rectangle'] == "on") $params['rectangle'] = 1;
        else $params['rectangle'] = null;
        $params['id_lot'] = $this->lot->getIdLot();
        $params['created_at'] = $this->echantillon->getCreatedAt();
        $params['updated_at'] = date('Y-m-d H:i:s', time());
        $params['id_user'] = $this->echantillon->getIdUser();
        $request->setParameter($this->form->getName(), $params);

        $this->processForm($request, $this->form);

        $this->setTemplate('edit');
    }

//  public function executeDelete(sfWebRequest $request)
//  {
//    $request->checkCSRFProtection();
//
//    $this->forward404Unless($echantillon = Doctrine_Core::getTable('echantillon')->find(array($request->getParameter('id_echantillon'))), sprintf('Object echantillon does not exist (%s).', $request->getParameter('id_echantillon')));
//    $echantillon->delete();
//
//    $this->redirect('echantillon/index');
//  }

    protected function processForm(sfWebRequest $request, sfForm $form)
    {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid())
        {
            $echantillon = $form->save();

            $this->redirect('echantillon/show?id_echantillon='.$echantillon->getIdEchantillon());
        }
    }
  
  
    public function executeListTraitement(sfWebRequest $request)
    {
        if ($request->isXmlHttpRequest())
        {
            $sSearch = $request->getParameter("sSearch");
            $iSortCol_0 = $request->getParameter("iSortCol_0");
            $sSortDir_0 = $request->getParameter("sSortDir_0");
            $iDisplayStart = $request->getParameter("iDisplayStart");
            $iDisplayLength = $request->getParameter("iDisplayLength");
            $page = number_format($iDisplayStart / $iDisplayLength) + 1;
            
            $echantillon = Doctrine_Core::getTable('echantillon')->find(array($request->getParameter('id_echantillon')));
            $this->lot = $echantillon->getLot();
            
            // On vérifie que l'utilisateur a les droits de lecture sur le lot concerné
            $this->droitLecture();
            
            $q = Doctrine_Core::getTable('traitement')->getTraitementEchantillonDatatable($echantillon->getIdEchantillon(), $echantillon->getIdLot(), $sSearch, $iSortCol_0, $sSortDir_0);
            
            
            $this->pager = new sfDoctrinePager(
                'traitementLot',
                sfConfig::get(2)
            );
            $this->pager->setQuery($q);
            $this->pager->setMaxPerPage($iDisplayLength);
            $this->pager->setMaxRecordLimit($iDisplayLength);
            $this->pager->setPage($page);
            $this->pager->init();
            
            $pager = $this->pager;

            $this->getContext()->getConfiguration()->loadHelpers('Url'); 
            $aaData = array();
            $list = $pager->getResults();
            foreach ($list as $v)
            {
                $lieu = "";
                if($v->getLieu()) $lieu = $v->getLieu()->getLibelle();
                
                $effectueSur = "";
                if($v->getIdEchantillon()) $effectueSur = "Echantillon";
                elseif($v->getIdLot()) $effectueSur = "Lot";
                elseif($v->getIdMesure()) $effectueSur = "Echantillon(Mesure N°".$v->getIdMesure().")";
                
                $ordre = "";
                if($v->getOrdre()) $ordre = $v->getOrdre();
                elseif($v->getDateDebutTraitement()) $ordre = $v->getDateTimeObject('date_debut_traitement')->format('d/m/Y');
                $success = "";
                if($v->getOk() == 1) $success = "Oui";
                elseif($v->getOk() == 0) $success = "Non";

                
                $consulter = '<a class="submit" href="'.url_for("traitement/show?id_traitement=".$v->getIdTraitement()).'">Consulter</a>';
                $aaData[] = array(
                    "0" => $ordre,
                    "1" => $v->getIdTraitement(),
                    "2" => $v->getTypeTraitement()->getLibelle(),
                    "3" => $v->getNumeroFicheMachine(),
                    "4" => $lieu,
                    "5" => $v->getDureeTraitementToString(),
                    "6" => $success,
                    "7" => $effectueSur,
                    "8" => $v->getCommentaire()->count(),
                    "9" => $consulter
                );
            }

            $output = array(
            "iTotalRecords" => count($pager),
            "iTotalDisplayRecords" => count($pager),
            "aaData" => $aaData,
            );

            return $this->renderText(json_encode($output));
        }
    }

    public function executeListMesure(sfWebRequest $request)
    {
        if ($request->isXmlHttpRequest())
        {
            $sSearch = $request->getParameter("sSearch");
            $iSortCol_0 = $request->getParameter("iSortCol_0");
            $sSortDir_0 = $request->getParameter("sSortDir_0");
            $iDisplayStart = $request->getParameter("iDisplayStart");
            $iDisplayLength = $request->getParameter("iDisplayLength");
            $page = number_format($iDisplayStart / $iDisplayLength) + 1;
            
            $echantillon = Doctrine_Core::getTable('echantillon')->find(array($request->getParameter('id_echantillon')));
            $this->lot = $echantillon->getLot();
            
            // On vérifie que l'utilisateur a les droits de lecture sur le lot concerné
            $this->droitLecture();
            
            $q = Doctrine_Core::getTable('mesure')->getMesureEchantillonDatatable($echantillon->getIdEchantillon(), $sSearch, $iSortCol_0, $sSortDir_0);
            
            
            $this->pager = new sfDoctrinePager(
                'mesureEchantillon',
                sfConfig::get(2)
            );
            $this->pager->setQuery($q);
            $this->pager->setMaxPerPage($iDisplayLength);
            $this->pager->setMaxRecordLimit($iDisplayLength);
            $this->pager->setPage($page);
            $this->pager->init();
            
            $pager = $this->pager;

            $this->getContext()->getConfiguration()->loadHelpers('Url'); 
            $aaData = array();
            $list = $pager->getResults();
            foreach ($list as $v)
            {
                $lieu = "";
                if($v->getLieu()) $lieu = $v->getLieu()->getLibelle();
                
                $methode = "";
                if($v->getIdMethodeMesure()) $methode = $v->getMethodeMesure()->getLibelle();
                
                $traitementAssocie = "";
                if($v->getIdTraitement() != null)
                {
                    $traitement = Doctrine_Core::getTable('traitement')->find(array($v->getIdTraitement()));
                    $traitementAssocie = $traitement->getTypeTraitement()->getLibelle();
                }
                $date = "";
                if($v->getDateMesure()) $date = $v->getDateTimeObject('date_mesure')->format('d/m/Y');
                $success = "";
                if($v->getOk() == 1) $success = "Oui";
                elseif($v->getOk() == 0) $success = "Non";
                $params = "";
                foreach($v->getMesureExploreParametre() as $mesureExploreParam)
                {
                    if($params == "") $params = $mesureExploreParam->getParametreExplore()->getLibelle();
                    else $params = $params.", ".$mesureExploreParam->getParametreExplore()->getLibelle();
                }
                
                $consulter = '<a class="submit" href="'.url_for("mesure/show?id_mesure=".$v->getIdMesure()).'">Consulter</a>';
                $aaData[] = array(
                    "0" => $v->getIdMesure(),
                    "1" => $methode,
                    "2" => $params,
                    "3" => $lieu,
                    "4" => $date,
                    "5" => $success,
                    "6" => $traitementAssocie,
                    "7" => $v->getCommentaire()->count(),
                    "8" => $consulter
                );
            }

            $output = array(
            "iTotalRecords" => count($pager),
            "iTotalDisplayRecords" => count($pager),
            "aaData" => $aaData,
            );

            return $this->renderText(json_encode($output));
        }
    }   
}
